package com.qf.springcloud.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class DynamicRouteFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 如果请求参数中携带一个  a=aa
        //1. 从Redis中获取路由规则(将规则存放到hash结构中)
        Map<Object, Object> map = redisTemplate.opsForHash().entries("dyroute");
        if(map != null && map.size() > 0){
            String serviceId = (String) map.get("serviceId");
            String path = (String) map.get("path");

            //2. 设置到RequestContext对象中
            RequestContext context = RequestContext.getCurrentContext();
            context.put(FilterConstants.SERVICE_ID_KEY,serviceId);
            context.put(FilterConstants.REQUEST_URI_KEY,path);
        }
        return null;
    }
}
